/**
 * @author zhengqi Wu
 * @version 1.0.0
 * @date 2021/4/29 15:55
 * @copyright MIN-Group:国家重大科技基础设施-未来网络北大实验室：深圳市信息论与未来网络重点实验室
 */
const SelfEncodingBase = require('../encoding/SelfEncodingBase').SelfEncodingBase
const Encoder = require('../encoding/Encoder').Encoder
const Block = require('../encoding/Block').Block
const TLV = require('../encoding/TLV')
const {TlvComponentBase,InitialAble} = require('./TlvComponentBase')
const aggregation = require('../common/aggregation')
const buffer2arraybuffer = require("../common/buffer2arraybuffer");
//实现了多继承

//
// 表示一个控制命令参数 CommonString
//
// @Description:
//
class ControlParameterCommonString extends aggregation(TlvComponentBase,InitialAble,SelfEncodingBase){
    constructor(){
        super()
        this.value = ""
    }

    getValue(){
        return this.value;
    }

    setValue(value){
        this.value = value
        this.doInitial()
    }

    // 将 ControlParameterCommonString 线速编码为一个TLV
    //
    // @Description:
    // @receiver c
    // @param encoder{Encoder}
    // @return int
    // @return error
    //
    wireEncode(encoder){
        let totalLength = 0
        try {
            //编码 TLV-VALUE
            let strBytes = Buffer.from(this.value)
            let byteArr = buffer2arraybuffer(strBytes)
            let tmpLen = encoder.prependByteArray(byteArr, byteArr.byteLength)
            totalLength += tmpLen

            // 编码 TLV-LENGTH
            tmpLen = encoder.prependVarNumber(BigInt(totalLength))
            totalLength += tmpLen

            // 编码 TLV-TYPE
            tmpLen = encoder.prependVarNumber(TLV.ComponentType.TlvManagementCommonString)
            totalLength += tmpLen

            return totalLength
        } catch (error) {
            throw error
        }
    }

    //
    // 从 TLV Block 中解码出一个 ControlParameterCommonString
    //
    // @Description:
    // @receiver c
    // @param block{Block}
    // @return error
    //
    wireDecode(block){
        try {
            // 检查 Type 是否正确
            if(TLV.expectType(block.getType(), TLV.ComponentType.TlvManagementCommonString)){
                let value = Buffer.from(block.getValue()).toString()
                this.setValue(value)
            }
        } catch (error) {
            throw error
        }
    }
}

module.exports = {
    ControlParameterCommonString:ControlParameterCommonString
}